package bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//bio实例  可以通过telnet 连接发送数据
public class demo {
    public static void main(String[] args) throws IOException {
        //1创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了");
        //2客户端链接，创建线程与之通讯
        while (true) {
            System.out.println("线程ID===" + Thread.currentThread().getId() + "   线程名字===" + Thread.currentThread().getName());
            //监听，等待客户端连接
            final Socket accept = serverSocket.accept();
            System.out.println("连接成功");
            //通过线程池创建线程与客户端通讯
            executorService.execute(new Runnable() {
                public void run() {
                    //3通讯
                    try {
                        //线程信息
                        byte[] bytes = new byte[1024];
                        System.out.println("线程ID===" + Thread.currentThread().getId() + "   线程名字===" + Thread.currentThread().getName());
                        //获取输入流
                        InputStream inputStream = accept.getInputStream();//没有消息阻塞在这里
                        while (true) {
                            System.out.println("read .....");
                            int read = inputStream.read(bytes);//返回读取了多少数据
                            if (read != -1) {//还有数据，可以继续读
                                System.out.println(new String(bytes, 0, read));//转换
                            } else {
                                break;
                            }
                        }
                    } catch (Exception e) {
                        System.out.println(e);
                    } finally {
                        System.out.println("关闭连接");
                        try {
                            accept.close();
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }
            });
        }

    }
}
